<template>
    <div class="edit-popup">
        <Popup ref="popupRef" :title="popupTitle" :async="true" width="1000px" @confirm="handleSubmit"
            @close="handleClose">
            <ElForm ref="formRef" :model="formData" label-width="180px">
                <ElFormItem label="支付名称" prop="pay_name">
                    <template #label> <span style="color: red;">*</span>支付名称:</template>
                    <ElInput v-model="formData.pay_name" clearable placeholder="请输入支付名称" />
                </ElFormItem>
                <el-form-item label="支付方式:" prop="sort">
                    <template #label> <span style="color: red;">*</span>支付方式:</template>
                    <el-radio-group v-model="formData.pay_method" class="ml-4">
                        <el-radio-button :label="1" size="large">微信支付</el-radio-button>
                        <el-radio-button :label="2" size="large">支付宝支付</el-radio-button>
                        <!-- <el-radio-button :label="3" size="large">微信支付子商户</el-radio-button> -->

                    </el-radio-group>
                </el-form-item>
                <!-- 微信支付 -->
                <template v-if="formData.pay_method == 1">
                    <ElFormItem label="支付商户号 (Mch_Id)" prop="wx_mchid">
                        <template #label> <span style="color: red;">*</span>支付商户号 (Mch_Id):</template>
                        <ElInput v-model="formData.wx_mchid" clearable placeholder="请输入支付商户号 (Mch_Id)" />
                    </ElFormItem>
                    <ElFormItem label="V3支付密钥 (APIKEY)" prop="wx_apikey">
                        <template #label> <span style="color: red;">*</span>V3支付密钥 (APIKEY):</template>
                        <ElInput v-model="formData.wx_apikey" clearable placeholder="请输入V3支付密钥 (APIKEY)" maxlength="32"
                            show-word-limit />
                    </ElFormItem>
                    <ElFormItem label="CERT文件证书" prop="wx_cert">
                        <template #label> <span style="color: red;">*</span> CERT文件证书:</template>
                        <el-upload ref="uploadRef" class="upload-demo" :action="uploadAction" :headers="uploadToken"
                            :on-success="successHandle1" :limit="1" :before-upload="handleBefore">
                            <el-input class="w-[280px]" :placeholder="formData.wx_cert" clearable readonly>
                                <template #append>
                                    <el-button>上传</el-button>
                                </template>
                            </el-input>
                        </el-upload>
                        <span>下载证书cert.zip中的 apiclient_cert.pem文件</span>
                    </ElFormItem>
                    <ElFormItem label="KEY文件证书" prop="wx_key">
                        <template #label> <span style="color: red;">*</span> KEY文件证书:</template>
                        <el-upload ref="uploadRef" class="upload-demo" :action="uploadAction" :headers="uploadToken"
                            :on-success="successHandle2" :limit="1" :before-upload="handleBefore">
                            <el-input class="w-[280px]" :placeholder="formData.wx_key" clearable readonly>
                                <template #append>
                                    <el-button>上传</el-button>
                                </template>
                            </el-input>
                        </el-upload>
                        <span>下载证书cert.zip中的 apiclient_key.pem文件</span>
                    </ElFormItem>
                    <ElFormItem label="微信支付公钥ID" prop="wx_mchid">
                        <ElInput v-model="formData.wx_public_cert_id" clearable placeholder="请输入微信支付公钥ID" />
                    </ElFormItem>
                    <ElFormItem label="微信支付公钥文件证书" prop="wx_key">
                        <el-upload ref="uploadRef" class="upload-demo" :action="uploadAction" :headers="uploadToken"
                            :on-success="successHandle6" :limit="1" :before-upload="handleBefore">
                            <el-input class="w-[280px]" :placeholder="formData.wx_public_cert_pem" clearable readonly>
                                <template #append>
                                    <el-button>上传</el-button>
                                </template>
                            </el-input>
                        </el-upload>
                        <span>下载证书cert.zip中的 pub_key.pem文件</span>
                    </ElFormItem>
                    <ElFormItem label="商户平台证书序列号" prop="wx_Serial">
                        <ElInput v-model="formData.wx_Serial" clearable placeholder="请输入商户平台证书序列号" />
                    </ElFormItem>
                </template>
                <!-- 支付宝支付 -->
                <template v-if="formData.pay_method == 2">
                    <ElFormItem label="应用appid" prop="mch_id">
                        <template #label> <span style="color: red;">*</span>应用appid:</template>
                        <div class="w-80">
                            <ElInput v-model="formData.ali_appid" clearable placeholder="请输入应用appid" />
                        </div>
                    </ElFormItem>
                    <ElFormItem label="应用私钥" prop="mch_id">
                        <template #label> <span style="color: red;">*</span>应用私钥:</template>
                        <div class="w-80">
                            <el-input class="w-[500px]" placeholder="请输入应用私钥" v-model="formData.ali_privatekey"
                                type="textarea" :rows="5">
                            </el-input>
                        </div>
                    </ElFormItem>
                    <ElFormItem label="应用公钥" prop="ali_pubkeycert">
                        <template #label> <span style="color: red;">*</span>应用公钥:</template>
                        <el-upload ref="uploadRef" class="upload-demo" :action="uploadAction" :headers="uploadToken"
                            :on-success="successHandle5" :limit="1" :before-upload="zfbhandleBefore">
                            <el-input class="w-[280px]" :placeholder="formData.ali_pubkeycert" clearable readonly>
                                <template #append>
                                    <el-button>上传</el-button>
                                </template>
                            </el-input>
                        </el-upload>
                        <span>下载证书应用公钥.crt</span>
                    </ElFormItem>
                    <ElFormItem label="支付宝公钥证书" prop="ali_public_key">
                        <template #label> <span style="color: red;">*</span>支付宝公钥证书:</template>
                        <el-upload ref="uploadRef" class="upload-demo" :action="uploadAction" :headers="uploadToken"
                            :on-success="successHandle3" :limit="1" :before-upload="zfbhandleBefore">
                            <el-input class="w-[280px]" :placeholder="formData.ali_public_key" clearable readonly>
                                <template #append>
                                    <el-button>上传</el-button>
                                </template>
                            </el-input>
                        </el-upload>
                        <span>下载证书支付宝公钥证书.crt</span>
                    </ElFormItem>
                    <ElFormItem label="支付宝根证书" prop="alirootcert">
                        <template #label> <span style="color: red;">*</span>支付宝根证书:</template>
                        <el-upload ref="uploadRef" class="upload-demo" :action="uploadAction" :headers="uploadToken"
                            :on-success="successHandle4" :limit="1" :before-upload="zfbhandleBefore">
                            <el-input class="w-[280px]" :placeholder="formData.alirootcert" clearable readonly>
                                <template #append>
                                    <el-button>上传</el-button>
                                </template>
                            </el-input>
                        </el-upload>
                        <span>下载证书支付宝根证书.crt</span>
                    </ElFormItem>
                    <el-form-item label="IP白名单:">
                        <div class="w-80">
                            <el-input class="w-[500px]" placeholder="请输入IP白名单" v-model="ip" disabled>
                            </el-input>
                        </div>
                        <el-button v-copy="ip" type="primary">复制</el-button>
                    </el-form-item>
                </template>
                <!-- 微信支付子商户  -->
                <!-- <template v-if="formData.pay_method == 3">
                    <ElFormItem label="服务商公众号 (Appid)" prop="fws_appid">
                        <template #label> <span style="color: red;">*</span>服务商公众号 (Appid):</template>
                        <ElInput v-model="formData.fws_appid" clearable placeholder="请输入服务商公众号 (Appid)" />
                    </ElFormItem>
                    <ElFormItem label="服务商支付商户号 (Mch_Id)" prop="fws_mchid">
                        <template #label> <span style="color: red;">*</span>服务商支付商户号 (Mch_Id):</template>
                        <ElInput v-model="formData.fws_mchid" clearable placeholder="请输入支付商户号 (Mch_Id)" />
                    </ElFormItem>
                    <ElFormItem label="公众号/小程序" prop="wx_apikey">
                        <template #label> <span style="color: red;">*</span>公众号/小程序 (Appid):</template>
                        <ElInput v-model="formData.wx_apikey" clearable placeholder="请输入子商户绑定的appid" show-word-limit />
                    </ElFormItem>
                    <ElFormItem label="支付商户号 (Mch_Id)" prop="wx_apikey">
                        <template #label> <span style="color: red;">*</span>支付商户号 (Mch_Id):</template>
                        <ElInput v-model="formData.wx_apikey" clearable placeholder="请输入子商户的sub_mch_id"
                            show-word-limit />
                    </ElFormItem>
                    <ElFormItem label="支付秘钥 (apikey)" prop="wx_apikey">
                        <template #label> <span style="color: red;">*</span>支付秘钥 (APIKEY):</template>
                        <ElInput v-model="formData.wx_apikey" clearable placeholder="请输入服务商支付秘钥" show-word-limit />
                    </ElFormItem>

                    <ElFormItem label="CERT文件证书" prop="wx_cert">
                        <template #label> <span style="color: red;">*</span> CERT文件证书:</template>
                        <el-upload ref="uploadRef" class="upload-demo" :action="uploadAction" :headers="uploadToken"
                            :on-success="successHandle1" :limit="1" :before-upload="handleBefore">
                            <el-input class="w-[280px]" :placeholder="formData.wx_cert" clearable readonly>
                                <template #append>
                                    <el-button>上传</el-button>
                                </template>
                            </el-input>
                        </el-upload>
                        <span>下载证书cert.zip中的 apiclient_cert.pem文件</span>
                    </ElFormItem>
                    <ElFormItem label="KEY文件证书" prop="wx_key">
                        <template #label> <span style="color: red;">*</span> KEY文件证书:</template>
                        <el-upload ref="uploadRef" class="upload-demo" :action="uploadAction" :headers="uploadToken"
                            :on-success="successHandle2" :limit="1" :before-upload="handleBefore">
                            <el-input class="w-[280px]" :placeholder="formData.wx_key" clearable readonly>
                                <template #append>
                                    <el-button>上传</el-button>
                                </template>
                            </el-input>
                        </el-upload>
                        <span>下载证书cert.zip中的 apiclient_key.pem文件</span>
                    </ElFormItem>
                    <ElFormItem label="微信支付公钥ID" prop="wx_mchid">
                        <ElInput v-model="formData.wx_public_cert_id" clearable placeholder="请输入微信支付公钥ID" />
                    </ElFormItem>
                    <ElFormItem label="微信支付公钥文件证书" prop="wx_key">
                        <el-upload ref="uploadRef" class="upload-demo" :action="uploadAction" :headers="uploadToken"
                            :on-success="successHandle6" :limit="1" :before-upload="handleBefore">
                            <el-input class="w-[280px]" :placeholder="formData.wx_public_cert_pem" clearable readonly>
                                <template #append>
                                    <el-button>上传</el-button>
                                </template>
                            </el-input>
                        </el-upload>
                        <span>下载证书cert.zip中的 pub_key.pem文件</span>
                    </ElFormItem>
                </template>
 -->




                <!-- 支付宝支付 -->
                <template v-if="formData.pay_method == 4">
                    <ElFormItem label="乐刷商户编号" prop="merchant_id">
                        <ElInput v-model="formData.merchant_id" clearable placeholder="请输入乐刷商户编号" />
                    </ElFormItem>
                    <el-form-item label="支付宝配置：" label-width="200px">
                        <div
                            style="width: 100%; border-radius: 3px;background: rgba(240, 250, 255, 1);border: 1px solid rgba(67, 144, 255, 1);text-indent: 2em;">
                            注意：如需使用乐刷的支付宝支付，请配置下方内容；如果仅使用微信支付则无需配置</div>
                    </el-form-item>
                    <el-form-item label-width="200px">
                        <el-form style="width: 100%; height: 150px;background: rgba(244, 246, 248, 1);" ref="formRef"
                            :model="formData" :rules="formRules">
                            <el-form-item label="支付宝开放平台APPID：" prop="ali_appid" label-width="250px"
                                style="margin-top: 20px;">
                                <el-input v-model="formData.ali_appid" clearable placeholder="支付宝开放平台APPID"
                                    style="width: 320px;" />
                            </el-form-item>
                            <!-- <el-form-item label="应用私钥（PRIVATE_KEY）：" prop="ali_public_key" label-width="250px" style="margin-top: 20px;">
                                <el-input
                                    v-model="formData.ali_appid"
                                    clearable
                                    placeholder="应用私钥（PRIVATE_KEY）"
                                    style="width: 320px;"
                                />
                            </el-form-item> -->
                        </el-form>
                    </el-form-item>
                </template>
            </ElForm>
        </Popup>
    </div>
</template>

<script lang="ts" setup name="payTemplateEdit">
import type { UploadProps } from 'element-plus'
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import {
    apiPayTemplateAdd,
    apiPayTemplateEdit,
    apiPayTemplateDetail,
    upload,
    getIp
} from '@/api/cloudupdate'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import { PayTypeEnumMap } from '@/enums/appEnums'
import { getToken } from "@/utils/auth";
import type { UploadInstance } from "element-plus";
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const ip = ref("")
const getiping = async () => {
    const results = await getIp({})
    ip.value = results.ip
}
getiping()
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑支付模板' : '新增支付模板'
})

// 表单数据
const formData = reactive({
    id: '',
    pay_name: '',
    pay_method: 1,
    pay_type: 1,
    wx_merchant_name: '',
    wx_appid: '',
    wx_miniapp_id: '',
    wx_mchid: '',
    wx_apikey: '',
    wx_cert: '',
    wx_key: '',
    wx_root: '',
    wx_sub_mch_id: '',
    wx_sub_appid: '',
    wx_sub_app_id: '',
    wx_sub_miniapp_id: '',
    wx_notifyx: '',
    ali_appid: '',
    ali_signtype: 2,
    ali_privatekey: '',
    ali_pubkeycert: '',
    ali_public_key: '',
    alirootcert: '',
    ali_notifyx: '',
    ali_returnx: '',
    log_switch: 1,
    merchant_id: "",
    wx_public_cert_id: "",
    wx_public_cert_pem: "",
    wx_Serial: '',
})


// 获取详情
const setFormData = async (row: Record<any, any>) => {
    const data = await apiPayTemplateDetail({ id: row.id })
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()

    if (formData.wx_apikey != '' && formData.wx_apikey.length != 32) {
        feedback.msgError('APIV3秘钥长度必须为32位');
        return false;
    }

    const data = { ...formData }



    mode.value == 'edit' ? await apiPayTemplateEdit(data) : await apiPayTemplateAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}
defineExpose({
    open,
    setFormData
})
interface uploadTokenObj {
    token: string;
}
const uploadRef = ref<UploadInstance>();
const uploadAction = `/adminapi/upload/localUpload`;
// const uploadAction = `https://saaskf.xiaojiangy.cn/adminapi/upload/localUpload`;
const uploadToken = ref<uploadTokenObj>({
    token: getToken(),
});


const handleBefore = (file: any) => {
    let acceptFileType = ['pem']

    let type = file.name.split(".").slice(-1)[0].toLowerCase()

    console.log(file);

    if (!acceptFileType.includes(type)) {
        feedback.msgError("上传文件失败,请上传正确的文件格式")
        return false
    }
    return true;
}
const zfbhandleBefore = (file: any) => {
    let acceptFileType = ['crt']

    let type = file.name.split(".").slice(-1)[0].toLowerCase()

    console.log(file);

    if (!acceptFileType.includes(type)) {
        feedback.msgError("上传文件失败,请上传正确的文件格式")
        return false
    }

    return true;

}
const successHandle1: UploadProps['onSuccess'] = (
    response: any,
    uploadFile: any
) => {
    formData.wx_cert = response.data.uri
}
const successHandle2: UploadProps['onSuccess'] = (
    response: any,
    uploadFile: any
) => {
    //   imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    //   console.log(uploadFile)
    formData.wx_key = response.data.uri
}
const successHandle3: UploadProps['onSuccess'] = (
    response: any,
    uploadFile: any
) => {
    console.log("123")
    formData.ali_public_key = response.data.uri
}
const successHandle4: UploadProps['onSuccess'] = (
    response: any,
    uploadFile: any
) => {
    formData.alirootcert = response.data.uri
}
const successHandle5: UploadProps['onSuccess'] = (
    response: any,
    uploadFile: any
) => {
    formData.ali_pubkeycert = response.data.uri
}
const successHandle6: UploadProps['onSuccess'] = (
    response: any,
    uploadFile: any
) => {
    formData.wx_public_cert_pem = response.data.uri
    console.log(formData.wx_public_cert_pem)
}
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>